<template>
  <div class='config-checkitem-container'>
    <el-row>
      <el-col :span="24">
        <el-form :inline="true"
                 label-width="100px"
                 :model="itemForm">
          <el-form-item label="检查项名称">
            <el-input v-model="checkItemList.check_item_name"
                      disabled></el-input>
          </el-form-item>

          <el-button type="primary"
                     icon="el-icon-plus"
                     @click="addCheckItem">新增</el-button>
        </el-form>
      </el-col>
      <el-col :span="24"
              class="checkItem-col">

        <el-form :inline="true"
                 :inline-message="true"
                 :rules="rules"
                 :model="checkItemList"
                 ref="ruleForm">
          <el-table :data="checkItemList.item_config"
                    class="checkItem-table"
                    height="600px"
                    :header-cell-style="{background:'#f5f5f5'}"
                    border
                    align="center"
                    row-key="check_item_id"
                    :indent="4"
                    :tree-props="{children:'children'}">

            <el-table-column label="参数名"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.content_name'>
                  <el-input v-model="scope.row.content_name"
                            size="mini"
                            @change="selectCode(scope,1)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="参数代码"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.content_code'>
                  <el-input v-model="scope.row.content_code"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="数据类型"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.data_type'>
                  <el-select v-model="scope.row.dataType"
                             value-key="value"
                             @change="selectDataType(scope.row)"
                             size="mini">
                    <el-option v-for="item in dataTypeCodeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="最大长度"
                             align="center">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input-number v-model="scope.row.max_length"
                                   :min="1"
                                   :controls="false"
                                   size="mini"></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- <el-table-column label="默认值"
                             align="center">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input v-model="scope.row.default_value"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column> -->
            <el-table-column label="字段控件"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.control_type'>
                  <el-select v-model="scope.row.controlType"
                             value-key="value"
                             @change="selectControlType(scope.row)"
                             size="mini">
                    <el-option v-for="item in scope.row.controlTypeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center"
                             label="内容配置">
              <template slot-scope="scope">
                <div class="config-btn">
                  <el-button type="primary"
                             v-if="scope.row.control_type==='3' || scope.row.control_type==='15'"
                             icon="el-icon-plus"
                             @click="configDataDialog(scope.row)"
                             size="mini">配置</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="控件配置"
                             align="center">
              <template slot-scope="scope">

                <el-form-item>
                  <el-button v-if="scope.row.controlType.content1=='array' || scope.row.controlType.content1=='object'"
                             type="primary"
                             icon="el-icon-plus"
                             size="mini"
                             @click="addChildItem(scope.row,scope.$index,scope)">配置子控件</el-button>
                  <el-button v-if="scope.row.controlType.content1=='listdrop' ||scope.row.controlType.content1=='checkbox'||scope.row.controlType.content1=='radio'"
                             type="primary"
                             icon="el-icon-plus"
                             size="mini"
                             @click="openConfig(scope.$index)">选项配置</el-button>
                  <el-input v-if="scope.row.control_type=='dictionary' "
                            v-model="scope.row.dictionary"
                            size="mini"
                            placeholder="请输入数据字典"></el-input>
                </el-form-item>
              </template>
            </el-table-column> -->
            <el-table-column label="字段校验"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.validate_type'>
                  <el-select v-model="scope.row.validateType"
                             placeholder="请选择"
                             value-key="value"
                             @change="selectCheckType(scope.row)"
                             size="mini">

                    <el-option v-for="item in scope.row.checkTypeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="排序"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.sort'>
                  <el-input v-model="scope.row.sort"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作"
                             align="center">
              <template slot-scope="scope">
                <el-tooltip content="删除"
                            placement="top">
                  <el-button type="text"
                             @click="deleteRow(scope.$index)">删除</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div class="btn-groups">
          <el-button @click="configItem"
                     type="primary">保存</el-button>
          <el-button @click="back">取消</el-button>
        </div>
      </el-col>

    </el-row>
    <el-dialog title="配置数据"
               :visible.sync="configDataDialogVisible">
      <el-radio-group v-model="choosedRow.origin_type"
                      @change="chooseOriginType">
        <el-radio v-for="item in dataOriginCode"
                  :key="item.code_id"
                  :label="item.value">{{item.name}}</el-radio>
      </el-radio-group>
      <el-input v-if="choosedRow.origin_type==='1'"
                placeholder="请输入标准码"
                v-model="choosedRow.origin_data[0].val"></el-input>
      <div class="config-data-container"
           v-if="choosedRow.origin_type==='2'">
        <div v-for="(item,index) in choosedRow.origin_data"
             :key="index"
             class="config-data">
          <el-input v-model="item.key"
                    placeholder="请输入自定义数据键名">
          </el-input>
          <el-input v-model="item.val"
                    placeholder="请输入自定义数据键值">
          </el-input>
          <i @click="addConfigData"
             v-if="index===0"
             class="fa fa-plus-circle"></i>
          <i @click="removeConfigData(index)"
             v-if="index!==0"
             class="fa fa-minus-circle"></i>
        </div>
      </div>
      <el-input v-if="choosedRow.origin_type==='3'"
                placeholder="请输入链接地址"
                v-model="choosedRow.origin_data[0].val"></el-input>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="configDataDialogVisible=false">取 消</el-button>
        <el-button @click="configData"
                   type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 拼音
import 'pinyin4js'
import { standardCodeApi } from '@/services/StandardCode'
import { CommonCheckApi } from '@/services/SystemSetting'
export default {
  data () {
    return {
      itemForm: {
        itemName: ''
      },
      rules: {
        param_type: [
          { required: true, message: '请选择参数分类', trigger: 'change' }
        ],
        content_name: [
          { required: true, message: '请输入参数名', trigger: 'blur' }
        ],
        content_code: [
          { required: true, message: '请输入参数代码', trigger: 'blur' }
        ],
        data_type: [
          { required: true, message: '请选择数据类型', trigger: 'change' }
        ],
        control_type: [
          { required: true, message: '请选择字段控件', trigger: 'change' }
        ],
        validate_type: [
          { required: true, message: '请选择字段校验', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      },
      // 检测值列表数据
      checkItemList: {
        check_item_id: '',
        check_item_name: '',
        item_config: []
      },
      // 配置数据来源时选中的行
      choosedRow: {},
      // 数据类型标准码列表
      dataTypeCodeList: [],
      // 数据类型标准码map
      dataTypeMap: new Map(),
      // 字段控件标准码列表
      controlTypeCodeList: [],
      // 字段控件标准码map
      controlTypeMap: new Map(),
      // 校验类型标准码列表
      checkTypeCodeList: [],
      // 校验类型标准码map
      checkTypeMap: new Map(),
      // 配置子控件弹框是否可见
      addChildItemDialogVisible: false,
      // 配置子控件数据对象
      childItemData: [],
      // 配置数据来源弹框是否可见
      configDataDialogVisible: false,
      // 数据来源标准码
      dataOriginCode: []
    }
  },
  methods: {
    back () {
      this.$router.go(-1)
    },
    // 打开配置数据来源弹框
    configDataDialog (row) {
      this.choosedRow = row

      this.configDataDialogVisible = true
    },
    // 配置数据来源
    configData () {
      if (this.choosedRow.origin_type === '1') {
        this.choosedRow.origin_data[0].key = 'code_type'
      } else if (this.choosedRow.origin_type === '3') {
        this.choosedRow.origin_data[0].key = 'url'
      }
      // 判断是否填写内容
      let list = this.choosedRow.origin_data
      // 判断key是否重复
      let dic = {}
      for (let i = 0; i < list.length; i++) {
        if (list[i]['key'] === '' || list[i]['val'] === '') {
          this.$message.warning('请完善数据配置')
          return
        }
        if (dic[list[i]['key']]) {
          this.$message.warning('键名不能重复')
          return
        } else {
          dic[list[i]['key']] = list[i]['key']
        }
      }
      this.configDataDialogVisible = false
    },
    // 选择数据来源类型
    chooseOriginType () {
      this.choosedRow.origin_data = [{
        key: '',
        val: ''
      }]
    },
    // 添加自定义数据
    addConfigData () {
      this.choosedRow.origin_data.push({
        key: '',
        val: ''
      })
    },
    // 删除自定义数据
    removeConfigData (index) {
      this.choosedRow.origin_data.splice(index, 1)
    },
    // 获取配置内容
    getConfigItem () {
      CommonCheckApi.getCheckItemContent({
        params: {
          check_item_id: this.checkItemList.check_item_id
        }
      }).then(res => {
        if (res.code === 0) {
          let list = []
          list = res.data.list
          list.map((item) => {
            item.dataType = this.dataTypeMap.get(item.data_type)
            item.controlType = this.controlTypeMap.get(item.control_type)
            item.validateType = this.checkTypeMap.get(item.validate_type)
            item.controlTypeList = this.controlTypeCodeList.filter((controlItem) => {
              return item.dataType.content2.includes(controlItem.value)
            })
            item.checkTypeList = this.checkTypeCodeList.filter((checkItem) => {
              return item.controlType.content2.includes(checkItem.value)
            })
            // item.dataType = this.dataTypeMap.get(item.data_type)
            // item.controlType = this.controlTypeMap.get(item.control_type)
            // item.checkType = this.checkTypeMap.get(item.check_type)
            if (!item.origin_data || item.origin_data.length <= 0) {
              item.origin_data = [{ key: '', val: '' }]
            }
            item.origin_type = item.origin_type || '1'
            item.origin_select_type = item.origin_select_type || ''
          })
          this.checkItemList.item_config = list
        }
      })
    },
    // 修改配置内容
    configItem () {
      let flag = true
      this.checkItemList.item_config.map((item) => {
        console.log(item, '1234')
        if (item.origin_select_type !== '' && !item.origin_data[0]['key']) {
          flag = false
        }
      })
      if (flag) {
        CommonCheckApi.updateCheckItemContent({
          data: this.checkItemList
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('修改配置成功')
            this.$router.push({
              path: '/checkItemManage'
            })
          }
        })
      } else {
        this.$message.warning('请完善数据配置')
      }

    },
    // 新增检查项
    addCheckItem () {
      // 获取最后一条的排序
      let sort = 1
      let len = this.checkItemList.item_config.length
      if (len > 0) {
        sort = Number(this.checkItemList.item_config[len - 1].sort) + 1
      }
      let item = {
        param_type: '',
        content_name: '',
        content_code: '',
        data_type: '',
        max_length: '',
        default_value: '',
        control_type: '',
        validate_type: '',
        sort: sort,
        children: [],
        controlTypeList: [],
        checkTypeList: [],
        controlType: {},
        validateType: {},
        dataType: {},
        origin_type: '1',
        origin_select_type: '',
        origin_data: [{ key: '', val: '' }]
      }
      this.checkItemList.item_config.push(item)
    },
    // 获取数据来源标准码
    getDataOriginCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'originType'
        }
      }).then(res => {
        //  console.log(res, 'get data type')
        if (res.code === 0 && res.data.list) {
          this.dataOriginCode = res.data.list
          window.localStorage.setItem('dataOriginCode', JSON.stringify(this.dataOriginCode))

        }
      })
    },
    // 获取数据类型标准码
    getDataTypeCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'data_type'
        }
      }).then(res => {
        //  console.log(res, 'get data type')
        if (res.code === 0 && res.data.list) {
          this.dataTypeCodeList = res.data.list
          window.localStorage.setItem('dataTypeCode', JSON.stringify(this.dataTypeCodeList))
          this.convertCodeListToMap(this.dataTypeMap, this.dataTypeCodeList)
        }
      })
    },
    // 数据类型下拉框选中事件
    selectDataType (row) {
      row.data_type = row.dataType.value
      // 根据选中的数据类型筛选出对应的控件类型列表
      row.controlTypeList = this.controlTypeCodeList.filter(item => {
        return row.dataType.content2.includes(item.value)
      })
      // 清空字段控件，字段校验数据
      row.control_type = ''
      row.controlType = {}
      row.validate_type = ''
      row.validateType = {}
      row.checkTypeList = []
    },
    // 获取字段控件标准码
    getControlTypeCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'field_control'
        }
      }).then(res => {
        // console.log(res, 'get control type')
        if (res.code === 0 && res.data.list) {
          this.controlTypeCodeList = res.data.list
          this.controlTypeCodeList = this.controlTypeCodeList.filter((item) => {
            return item.content3 === '0'
          })
          window.localStorage.setItem('controlTypeCode', JSON.stringify(res.data.list))
          this.convertCodeListToMap(this.controlTypeMap, this.controlTypeCodeList)
        }
      })
    },
    // 控件类型下拉框选中事件
    selectControlType (row) {
      row.control_type = row.controlType.value
      if (row.controlType.value === '3' || row.controlType.value === '15') {
        row.origin_select_type = row.controlType.value
      }

      // 根据选中的控件类型筛选出对应的校验类型
      row.validate_type = ''
      row.validateType = {}
      row.checkTypeList = this.checkTypeCodeList.filter(item => {
        return row.controlType.content2.includes(item.value)
      })
    },
    // 获取字段校验标准码
    getCheckTypeCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'field_check'
        }
      }).then(res => {
        // console.log(res, 'get control type')
        if (res.code === 0 && res.data.list) {
          this.checkTypeCodeList = res.data.list
          window.localStorage.setItem('checkTypeCode', JSON.stringify(this.checkTypeCodeList))
          this.convertCodeListToMap(this.checkTypeMap, this.checkTypeCodeList)
        }
      })
    },
    // 选择校验类型下拉框选中事件
    selectCheckType (row) {
      row.validate_type = row.validateType.value
    },
    // 将标准码列表转换为map
    convertCodeListToMap (map, codeList) {
      codeList.map((item) => {
        map.set(item.value, item)
      })
    },
    // 参数代码
    selectCode (scope, num) {
      let i = scope.$index
      let data = scope.row.content_name
      scope.row.content_code = PinyinHelper.getShortPinyin(data)
    },
    deleteRow (index, arr, id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.checkItemList.item_config.splice(index, 1)
      }).catch(() => {

      })
    },
  },
  async created () {
    // 判断是否缓存了标准码数据，是则直接使用缓存，否则请求接口
    this.checkItemList.check_item_id = this.$route.query.id
    this.checkItemList.check_item_name = this.$route.query.name

    let dataOriginCode = window.localStorage.getItem('dataOriginCode')
    let dataTypeCode = window.localStorage.getItem('dataTypeCode')
    let controlTypeCode = window.localStorage.getItem('controlTypeCode')
    let checkTypeCode = window.localStorage.getItem('checkTypeCode')
    if (dataOriginCode) {
      this.dataOriginCode = JSON.parse(dataOriginCode)
    } else {
      await this.getDataOriginCode()
    }
    if (dataTypeCode) {
      this.dataTypeCodeList = JSON.parse(dataTypeCode)
      this.convertCodeListToMap(this.dataTypeMap, this.dataTypeCodeList)
    } else {
      await this.getDataTypeCode()
    }
    if (controlTypeCode) {
      this.controlTypeCodeList = JSON.parse(controlTypeCode)
      this.controlTypeCodeList = this.controlTypeCodeList.filter((item) => {
        return item.content3 === '0'
      })
      this.convertCodeListToMap(this.controlTypeMap, this.controlTypeCodeList)
    } else {
      await this.getControlTypeCode()
    }
    if (checkTypeCode) {
      this.checkTypeCodeList = JSON.parse(checkTypeCode)
      this.convertCodeListToMap(this.checkTypeMap, this.checkTypeCodeList)
    } else {
      await this.getCheckTypeCode()
    }
    this.getConfigItem()
  },
  mounted () {
  }
}
</script>
<style scoped lang='scss'>
.config-checkitem-container {
  padding: 20px;
  .btn-groups {
    margin-top: 20px;
    width: 100%;
    text-align: center;
  }
  .config-btn {
    text-align: center;
  }
}
.el-radio-group {
  margin-bottom: 20px;
}
.config-data-container {
  height: 400px;
  overflow-y: scroll;
  .config-data {
    display: flex;
    align-items: center;
    .el-input {
      width: 300px;
      margin-right: 20px;
      margin-bottom: 20px;
    }
    .fa {
      font-size: 30px;
      position: relative;
      top: -11px;
      cursor: pointer;
    }
  }
}
</style>
